import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false,
    role: null,
    token: null,
    avatarUrl: null,
    defaultAvatar: '/assets/default-avatar.png',
    error: null
  }),

  getters: {
    getUserInfo: (state) => state.userInfo,
    getIsLoggedIn: (state) => state.isLoggedIn,
    getRole: (state) => state.role,
    isAdmin: (state) => state.role === 'admin',
    getAvatar: (state) => {
      console.log('获取头像路径:', {
        avatarUrl: state.avatarUrl,
        defaultAvatar: state.defaultAvatar,
        userInfo: state.userInfo
      })
      // 优先使用 userInfo.avatar
      if (state.userInfo?.avatar) {
        return state.userInfo.avatar
      }
      // 其次使用 avatarUrl
      if (state.avatarUrl) {
        return state.avatarUrl
      }
      // 最后使用默认头像
      return state.defaultAvatar
    },
    getError: (state) => state.error
  },

  actions: {
    async login(username, password) {
      try {
        this.error = null
        console.log('=== 开始登录请求 ===')
        console.log('登录请求参数:', {
          username,
          password: '******' // 出于安全考虑，不打印实际密码
        })
        
        // 登录请求
        const response = await axios.post('http://localhost:8080/user/login', {
          username,
          password
        })
        
        console.log('登录响应数据:', {
          token: response.data.token,
          role: response.data.role,
          status: response.status,
          headers: response.headers,
          responseData: response.data // 打印完整的响应数据
        })
        
        // 登录时拿到 token 并存储在 store 和 localStorage
        this.token = response.data.token
        this.role = response.data.role
        this.isLoggedIn = true
        
        // 获取用户详细信息
        console.log('=== 开始获取用户详细信息 ===')
        try {
          // 获取所有用户
          const allUsersResponse = await axios.get('http://localhost:8080/user/user_findall')
          console.log('所有用户数据:', allUsersResponse.data)
          
          // 打印所有用户的用户名，用于调试
          console.log('所有用户名列表:', allUsersResponse.data.map(u => u.username))
          
          // 根据用户名查找用户
          const user = allUsersResponse.data.find(u => {
            console.log('比较用户名:', {
              inputUsername: username,
              currentUsername: u.username,
              isMatch: u.username === username
            })
            return u.username === username
          })
          
          if (user) {
            // 确保用户信息包含角色信息
            const userInfo = {
              ...user,
              role: this.role // 使用登录响应中的角色信息
            }
            
            console.log('找到匹配的用户信息:', {
              userId: userInfo.userId,
              username: userInfo.username,
              role: userInfo.role,
              avatar: userInfo.avatar,
              // 其他敏感信息不打印
            })
            
            this.userInfo = userInfo
            
            if (this.userInfo.avatar) {
              console.log('设置头像路径:', this.userInfo.avatar)
              this.avatarUrl = this.userInfo.avatar
              console.log('头像URL:', this.avatarUrl)
            } else {
              console.log('用户没有头像路径，使用默认头像')
            }
            
            console.log('=== 登录流程完成 ===')
            console.log('当前用户状态:', {
              isLoggedIn: this.isLoggedIn,
              role: this.role,
              hasToken: !!this.token,
              hasUserInfo: !!this.userInfo,
              userInfo: this.userInfo // 打印完整的用户信息
            })
            
            return { success: true }
          } else {
            console.error('未找到匹配的用户信息，输入的用户名:', username)
            throw new Error('未找到用户信息')
          }
        } catch (userError) {
          console.error('获取用户信息失败:', userError)
          throw new Error(userError.response?.data?.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('登录失败:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status
        })
        this.error = error.response?.data?.message || error.message || '网络错误，请稍后重试'
        return { success: false, error: this.error }
      }
    },

    logout() {
      console.log('=== 开始登出操作 ===')
      console.log('登出前的状态:', {
        isLoggedIn: this.isLoggedIn,
        role: this.role,
        hasToken: !!this.token,
        hasUserInfo: !!this.userInfo
      })
      
      // 清除所有状态
      this.userInfo = null
      this.isLoggedIn = false
      this.role = null
      this.token = null
      this.avatarUrl = null
      this.error = null
      
      // 清除所有存储
      localStorage.removeItem('user-token')
      localStorage.removeItem('user')
      
      // 清除axios默认header
      delete axios.defaults.headers.common['Authorization']
      
      // 重置所有状态
      this.$reset()
      
      console.log('=== 登出完成 ===')
      console.log('登出后的状态:', {
        isLoggedIn: this.isLoggedIn,
        role: this.role,
        hasToken: !!this.token,
        hasUserInfo: !!this.userInfo
      })
    },

    async updateUserInfo(userData) {
      try {
        this.error = null
        console.log('更新用户信息:', userData)
        const response = await axios.post('http://localhost:8080/user/user_update', userData)
        if (response.status === 200) {
          console.log('用户信息更新成功:', response.data)
          this.userInfo = { ...this.userInfo, ...userData }
          if (userData.avatar) {
            console.log('更新头像路径:', userData.avatar)
            this.avatarUrl = userData.avatar
            console.log('新的头像URL:', this.avatarUrl)
          }
          return { success: true }
        }
        return { success: false, error: '更新失败' }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        this.error = error.response?.data?.message || '网络错误，请稍后重试'
        return { success: false, error: this.error }
      }
    },

    async fetchUserInfo(username) {
      try {
        this.error = null
        console.log('获取用户信息:', username)
        const allUsersResponse = await axios.get('http://localhost:8080/user/user_findall')
        const user = allUsersResponse.data.find(u => u.username === username)
        
        if (user) {
          console.log('获取到的用户信息:', user)
          this.userInfo = user
          if (this.userInfo.avatar) {
            console.log('设置头像路径:', this.userInfo.avatar)
            this.avatarUrl = this.userInfo.avatar
            console.log('头像URL:', this.avatarUrl)
          } else {
            console.log('用户没有头像路径，使用默认头像')
          }
          return { success: true }
        }
        return { success: false, error: '未找到用户信息' }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.error = error.response?.data?.message || '网络错误，请稍后重试'
        return { success: false, error: this.error }
      }
    },

    async updateAvatar(avatarFile) {
      try {
        console.log('开始更新头像')
        const formData = new FormData()
        formData.append('avatar', avatarFile)
        
        const response = await axios.post('http://localhost:8080/user/update_avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (response.status === 200) {
          console.log('头像更新响应:', response.data)
          this.avatarUrl = response.data.avatar
          console.log('新的头像URL:', this.avatarUrl)
          return true
        }
        return false
      } catch (error) {
        console.error('更新头像失败:', error)
        return false
      }
    },

    clearError() {
      this.error = null
    }
  },

  persist: {
    key: 'user',
    storage: localStorage,
    paths: ['userInfo', 'isLoggedIn', 'role', 'token', 'avatarUrl']
  }
})
